package top.tupobi.zing.adapter;

import android.annotation.SuppressLint;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import top.tupobi.zing.R;
import top.tupobi.zing.mvp.model.FriendModel;
import top.tupobi.zing.mvp.model.UserExt;
import top.tupobi.zing.network.HttpConfig;
import top.tupobi.zing.utils.UT;

public class AdapterRvFriendList extends RecyclerView.Adapter<AdapterRvFriendList.ItemViewHolder> {

    private List<FriendModel> mFriendList = new ArrayList<>();

    @NonNull
    @Override
    public ItemViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ItemViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_of_rv_friend_list, parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull ItemViewHolder holder, int position) {

        final float[] itemTouchStartX = new float[1];
        final float[] itemTouchStartY = new float[1];
        final long[] itemTouchStartTime = new long[1];

        holder.itemView.setOnTouchListener(new View.OnTouchListener() {
            @SuppressLint("ClickableViewAccessibility")
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                switch (action & MotionEvent.ACTION_MASK) {
                    case MotionEvent.ACTION_POINTER_DOWN:
                        //除了第一个手指以外的手指按下
                        LogUtils.e("another pointer down");
                        normalItem(v);
                        break;
                    case MotionEvent.ACTION_DOWN:
                        LogUtils.e("first pointer down");
                        activeItem(v);
                        itemTouchStartX[0] = event.getX();
                        itemTouchStartY[0] = event.getY();
                        itemTouchStartTime[0] = System.currentTimeMillis();
                        return true;
                    case MotionEvent.ACTION_MOVE:
                        //及其微小不算移动，active item
                        float itemTouchEndX = event.getX();
                        float itemTouchEndY = event.getY();
                        float itemTouchDistanceX = Math.abs(itemTouchEndX - itemTouchStartX[0]);
                        float itemTouchDistanceY = Math.abs(itemTouchEndY - itemTouchStartY[0]);
                        double itemTouchDistance = Math.sqrt(itemTouchDistanceX * itemTouchDistanceX + itemTouchDistanceY * itemTouchDistanceY);
                        if (itemTouchDistance <= 1) {
                            LogUtils.e("不算移动");
                            if (itemTouchEndX < 0 || itemTouchEndY < 0) {
                                normalItem(v);
                                event.setAction(MotionEvent.ACTION_UP);
                                return true;
                            }
                        } else {
                            normalItem(v);
                            if (itemTouchStartX[0] - itemTouchEndX > 40) {
                                mOnItemTouchCallback.onCloseMenu();
                                return true;
                            }
                            if (itemTouchEndX < 0 || itemTouchEndY < 0) {
                                event.setAction(MotionEvent.ACTION_UP);
                                return true;
                            }
                        }
                        return true;
                    case MotionEvent.ACTION_UP:
                        // 滑动事件一旦交给父控件就拿不回来了，在整个滑动过程中，可能按下是自己处理，后面全由父控件处理
                        // 但是父控件开始处理的时候，没有子控件处理的信息，要手动处理下。抬起操作都由子控件处理，如果到抬起传递给父控件可能父控件没有前面的滑动信息什么也做不了。
                        LogUtils.e("item up");
                        normalItem(v);
                        itemTouchEndX = event.getX();
                        itemTouchEndY = event.getY();
                        itemTouchDistanceX = Math.abs(itemTouchEndX - itemTouchStartX[0]);
                        itemTouchDistanceY = Math.abs(itemTouchEndY - itemTouchStartY[0]);
                        itemTouchDistance = Math.sqrt(itemTouchDistanceX * itemTouchDistanceX + itemTouchDistanceY * itemTouchDistanceY);
                        long upTimeDistance = System.currentTimeMillis() - itemTouchStartTime[0];
                        if (upTimeDistance < 50 || itemTouchDistance <= 1) {
                            if (mOnItemTouchCallback != null) {
                                mOnItemTouchCallback.onClick(v, mFriendList.get(position));
                            }
                        } else {
                            if (itemTouchStartX[0] - event.getX() > 40) {
                                if (mOnItemTouchCallback != null) {
                                    mOnItemTouchCallback.onCloseMenu();
                                }
                            }
                        }
                        return true;
                    case MotionEvent.ACTION_CANCEL:
                        normalItem(v);
                        LogUtils.e("action cancel");
                }
                return true;
            }
        });

        FriendModel friendModel = mFriendList.get(position);
        String avatarUrl = friendModel.getFriendAvatarUrl();
        if (!StringUtils.isEmpty(avatarUrl)) {
            Glide.with(holder.itemView).load(HttpConfig.PIC_ROOT + avatarUrl).into(holder.civ_avatar);
        }
        String friendNickname = friendModel.getFriendNickname();
        if (StringUtils.isEmpty(friendNickname)) {
            holder.tv_nickname.setText(friendModel.getFriendUsername());
        } else {
            holder.tv_nickname.setText(friendNickname);
        }

        String friendLatestMsg = friendModel.getFriendLatestMsg();
        if (StringUtils.isEmpty(friendLatestMsg)) {
            holder.tv_message_content.setText("");
        } else {
            if (friendLatestMsg.length() > 10) {
                friendLatestMsg = friendLatestMsg.substring(0, 10) + "...";
            }
            holder.tv_message_content.setText(friendLatestMsg);
        }

        String friendLatestMsgDatetime = friendModel.getFriendLatestMsgDatetime();
        if (!StringUtils.isEmpty(friendLatestMsgDatetime)) {
            if (UT.isInSameDay(friendLatestMsgDatetime)) {
                holder.tv_message_date.setText(friendLatestMsgDatetime.substring(11, 16));
            } else {
                holder.tv_message_date.setText(friendLatestMsgDatetime.substring(0, 10));
            }
        } else {
            holder.tv_message_date.setText("");
        }

//        Integer friendUnreceivedMsgCount = friendModel.getFriendUnreceivedMsgCount();
//        if (friendUnreceivedMsgCount == null) {
//            holder.tv_message_count.setText("0");
//        } else {
//            holder.tv_message_count.setText("" + friendUnreceivedMsgCount);
//        }
        String friendExt = friendModel.getFriendExt();
        if (!StringUtils.isEmpty(friendExt)) {
            UserExt userExt = new Gson().fromJson(friendExt, UserExt.class);
            if (userExt.isOnline()) {
                holder.tv_friend_online.setText("(在线)");
            } else {
                holder.tv_friend_online.setText("(离线)");
            }
        }

    }

    private void normalItem(View v) {
        v.setBackgroundColor(0x00000000);
    }

    private void activeItem(View v) {
        v.setBackgroundColor(0x50ffffff);
    }

    @Override
    public int getItemCount() {
        return mFriendList.size();
    }

    static class ItemViewHolder extends RecyclerView.ViewHolder {

        private CircleImageView civ_avatar;
        private TextView tv_nickname, tv_message_date, tv_friend_online, tv_message_content;

        ItemViewHolder(@NonNull View itemView) {
            super(itemView);
            civ_avatar = itemView.findViewById(R.id.civ_avatar);
            tv_nickname = itemView.findViewById(R.id.tv_nickname);
            tv_message_date = itemView.findViewById(R.id.tv_message_date);
            tv_friend_online = itemView.findViewById(R.id.tv_friend_online);
            tv_message_content = itemView.findViewById(R.id.tv_message_content);
        }
    }


    private OnItemTouchCallback mOnItemTouchCallback;

    public void setOnItemTouchCallback(OnItemTouchCallback onItemTouchCallback) {
        mOnItemTouchCallback = onItemTouchCallback;
    }

    public void notifyFriendListChanged(List<FriendModel> friendList) {
        mFriendList = friendList;
        notifyDataSetChanged();
    }

}


